package ch.manage.movie.downloader;

import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xml.sax.InputSource;

import ch.manage.movie.business.Movie;

public class Downloader implements IDownloader{

	

	private void putURLInClipBoard(String url) {
		Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
	               new StringSelection(url), null
	          );
		
	}
	
	public static void main(String[] args){
		Downloader d = new Downloader();
		Movie m = new Movie();
		m.setTitle("Leavin las Vegas");
		try {
			d.getMovieURL(MovieDownloadPages.HD_World, m);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public String getMovieURL(MovieDownloadPages downloadPage, Movie movieToDownload) throws Exception {
		
		URL url = new URL(URLConstructor.construct(movieToDownload.getTitle(), downloadPage));
		
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setRequestProperty("User-Agent", "manageMovies Mozilla/5.0");
        
        String contentType = conn.getContentType();
        if (contentType == null || !contentType.startsWith("text/html")) {
            return null;
        }
            
        BufferedInputStream is = null;
        try {
            is = new BufferedInputStream(conn.getInputStream());
			int readChar = 0;
			StringBuilder b = new StringBuilder();
            while (readChar != -1) {
				readChar = is.read();
				b.append((char)readChar);
			}
            
            String toParse = null;
            
            switch(downloadPage){
            case HD_Area:
            	toParse =evaluateCommentBox(b.toString());
            	break;
            case HD_World:
            	toParse = b.toString();
            }
            
            InputStream s = new ByteArrayInputStream(toParse.getBytes());
            Document doc = Jsoup.parse(s , null, toParse);
            Elements links = doc.select("a[href]");
            is.close();
            for (Element link : links) {
                String linkString = link.absUrl("href");
                String regex = movieToDownload.getTitle().split(" ")[0].toLowerCase();
                if (linkString.startsWith("http") && linkString.contains(regex)) {
                	getNetloadUrlAndCopyInClipBoard(linkString, movieToDownload.getTitle());
                }
            }
        } finally {
            is.close();
        }
        
        return "blub";
	}
	
	private void getNetloadUrlAndCopyInClipBoard(String baseUrl, String movieName) throws Exception{
		URL url = new URL(baseUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setRequestProperty("User-Agent", "manageMovies Mozilla/5.0");
        
		String contentType2 = conn.getContentType();
		if (true) {
			BufferedInputStream is = null;
			try {
				is = new BufferedInputStream(conn.getInputStream());
				
				int readChar = 0;
				StringBuilder b = new StringBuilder();
	            while (readChar != -1) {
					readChar = is.read();
					b.append((char)readChar);
				}
	            String toParse = evaluateHDWorldLink(b.toString());
	            InputStream s = new ByteArrayInputStream(toParse.getBytes());
				
				Document doc = Jsoup.parse(s, null, toParse);
				Elements links = doc.select("a[href]");
				List<String> linksFound = new ArrayList<String>();
					String linkString = links.get(1).absUrl("href");
					if (linkString.startsWith("http")) {
						putURLInClipBoard(linkString);
						System.out.println("Successfully added Link for movie: "+movieName);
						System.out.println("Found link under: "+linkString);
					}
//				}

			}

			catch (Exception e) {

			}
			conn.disconnect();
		}
        
	}
	
	private String evaluateCommentBox(String htmlCode){
		int startIndex = htmlCode.lastIndexOf("<!-- If Suchergebnisse Anfang -->");
		int endInex = htmlCode.lastIndexOf("<!-- If Suchergebnisse Ende -->");
		String ret =htmlCode.substring(startIndex, endInex);
		return ret;
	}
	
	
	private String evaluateHDWorldLink(String htmlCode){
		int startIndex = htmlCode.lastIndexOf("<strong>Dauer: </strong>");
		int endInex = htmlCode.lastIndexOf("<strong>Passwort: </strong>");
		String ret =htmlCode.substring(startIndex, endInex);
		return ret;
	}
	
	
	

}
